package com.pk.serviceprovider;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

interface ServiceProvider {
    Service newService();
}

public class Services {
    private static class DefaultService implements Service {
        @Override
        public void doService() {
            System.out.println("default service do...");
        }
    }

    private static final String DEFAULT_NAME = "DEFAULT_NAME";
    private static Map<String, ServiceProvider> mapProvider = new ConcurrentHashMap<>();


    protected Services() {
    }

    public static void registerProvider(String name, ServiceProvider serviceProvider) {
        mapProvider.put(name, serviceProvider);
    }

    public static void unRegisterProvider(String name) {
        mapProvider.remove(name);
    }

    public static void unAllRegisterProvider() {
        mapProvider.clear();
    }

    public static Service newInstance() {
        return new DefaultService();
    }

    public static Service newInstance(String name) throws Exception {
        ServiceProvider serviceProvider = mapProvider.get(name);
        if (serviceProvider == null) {
            throw new Exception("ServiceProvider is null");
        }
        return serviceProvider.newService();
    }

}
